﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using System.Xml.Serialization;
using ClientWPF.BankService;
using CryptoModule;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Editors;
using Microsoft.Win32;

namespace ClientWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly ObservableCollection<Bank> banks;
        private ObservableCollection<Deposit> userDeposits;
        private ObservableCollection<Partner> partners;
        private readonly BankServiceClient bankServiceClient;
        private static byte[] privateKey;
        private Generators generator;
        private string clientName;
        private string clientUnp;
        private Guid clientId;
        private readonly Log log;

        protected static byte[] PrivateKey
        {
            get { return privateKey ?? (privateKey = ReadPrivateKey()); }
        }

        protected static string PrivateKeyPath
        {
            get
            {
                return "privateKey";
            }
        }

        protected Generators Generator
        {
            get { return generator ?? (generator = new Generators(bankServiceClient)); }
        }

        public MainWindow()
        {
            try
            {
                log = new Log();
                InitializeComponent();
                clientId = Guid.Empty;
                LoadClientInfo();
                FillPoFormWithClientInfo();
                dateEditDate.Text = DateTime.Today.ToShortDateString();
                bankServiceClient = new BankServiceClient();
                banks = new ObservableCollection<Bank>(bankServiceClient.GetBanksList());
                comboBoxEditBenefBank.ItemsSource = banks;
                if (clientId != Guid.Empty)
                {
                    LoadData();
                }
                textEditPaymentOrderNumber.Text = Generator.PaymentOrderNumberGenerator(Decimal.Parse(textEditPayerUNP.Text)).ToString();
            }
            catch (Exception exception)
            {
                log.WriteToLog(exception);
            }
        }

        private void LoadData()
        {
            userDeposits = new ObservableCollection<Deposit>(bankServiceClient.GetClientDeposits(clientId));
            partners = new ObservableCollection<Partner>(bankServiceClient.GetClientPartners(clientId));
            comboBoxEditPayerDepositNumber.ItemsSource = userDeposits;
            comboBoxEditBenefName.ItemsSource = partners;
            comboBoxEditPayerDepositNumber.IsTextEditable = true;
            comboBoxEditBenefName.IsTextEditable = true;
        }

        private void FillPoFormWithClientInfo()
        {
            textEditPayerName.Text = clientName;
            textEditPayerUNP.Text = clientUnp;
        }

        private void LoadClientInfo()
        {
            try
            {
                XElement root = XDocument.Load("clientInfo.xml").Root;
                if (root != null)
                {
                    // ReSharper disable PossibleNullReferenceException
                    clientName = root.Element("Name").Value;
                    clientUnp = root.Element("UNP").Value;
                    clientId = new Guid(root.Element("Id").Value);
                    // ReSharper restore PossibleNullReferenceException
                }
            }
            catch (Exception)
            {
                DXMessageBox.Show("Файл конфигурации пользователя не найден или повреждён", "Ошибка",
                                  MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void ComboBoxEditBenefDepositNumber_SelectedIndexChanged(object sender, RoutedEventArgs e)
        {
            if (comboBoxEditBenefDepositNumber.SelectedIndex != -1)
            {
                int index = -1;
                foreach (var bank in banks)
                {
                    index++;
                    if (bank.Name == ((PartnerDeposit)comboBoxEditBenefDepositNumber.SelectedItem).Bank.Name)
                    {
                        break;
                    }
                }
                comboBoxEditBenefBank.SelectedIndex = index;
            }
            textEditBenefDepositNumber.Text = ((PartnerDeposit) comboBoxEditBenefDepositNumber.SelectedItem).Number.ToString();
        }

        private void ComboBoxEditBenefNameSelectedIndexChanged(object sender, RoutedEventArgs e)
        {
            if (comboBoxEditBenefName.SelectedItem != null)
            {
                textEditBenefName.Text = ((Partner)comboBoxEditBenefName.SelectedItem).Name;
            }
            //Partner curBenef = null;
            //if (comboBoxEditBenefName.SelectedIndex != -1)
            //{
            //    curBenef = (Partner) comboBoxEditBenefName.SelectedItem;
            //}
            //if (comboBoxEditBenefName.SelectedIndex != -1)
            //{
            //    int index = -1;
            //    if (curBenef != null)
            //        foreach (var dep in curBenef.PartnerDeposits)
            //        {
            //            index++;
            //            if (dep.Number == ((PartnerDeposit)comboBoxEditBenefDepositNumber.SelectedItem).Bank.Name)
            //            {
            //                break;
            //            }
            //        }
            //    comboBoxEditBenefBank.SelectedIndex = index;
            //}
        }

        private void ButtonSendPO_Click(object sender, RoutedEventArgs e)
        {
            List<string> errLst = ValidatePaymentOrderForm();

            if (errLst.Count > 0)
            {
                ShowErrors(errLst);
            }
            else
            {
                PaymentOrder po = ParsePaymentOrder();

                var hash = MD5Crypto.MD5Encode(GeneratePaymentOrderFieldsHash(po));
                var rsa = new RSASignature();
                var eds = rsa.CreateSignature(hash, PrivateKey);
                StateAndReason stateAndReason = bankServiceClient.AddPaymentOrder(po, eds);
                if (stateAndReason.PaymentOrderState.TransactionState.Equals("принято"))
                {
                    DXMessageBox.Show("Транзакция прошла успешно - платёжное поручение принято. ", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    ClearPaymentOrderForm();
                }
                else
                {
                    DXMessageBox.Show("Ошибка во время выполнения транзакции - платёжное поручение не принято. \n" + stateAndReason.Reason, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }

        //Note: there is the method analog on the service side, change both(!)
        private static byte[] GeneratePaymentOrderFieldsHash(PaymentOrder po)
        {
            var sb = new StringBuilder();

            sb.Append(po.Number.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.Date.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.Urgent);
            sb.Append(po.SumCurrencyText);
            sb.Append(po.Currency.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.Sum.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.Payer);
            sb.Append(po.PayerDepositNumber.ToString(CultureInfo.InvariantCulture));
            //miss textEditPayerBank.Text - it's our bank always
            //miss textEditPayerBankCode.Text - it's our bank always
            sb.Append(po.BenefBankName);
            sb.Append(po.BenefBankCode);
            sb.Append(po.Benefeciar);
            sb.Append(po.BenefDepNum.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.PaymentAllocation);
            sb.Append(po.PayerUNP.ToString(CultureInfo.InvariantCulture));
            sb.Append(po.BenefUNP.ToString(CultureInfo.InvariantCulture));

            var encoding = new UTF8Encoding();
            return encoding.GetBytes(sb.ToString());
        }

        private PaymentOrder ParsePaymentOrder()
        {
            int i;
            DateTime dt;
            decimal d;

            var po = new PaymentOrder();

            if (int.TryParse(textEditPaymentOrderNumber.Text, out i)) po.Number = i;
            if (DateTime.TryParse(dateEditDate.Text, out dt)) po.Date = dt;
            po.Urgent = checkBoxUrgent.IsChecked.HasValue && checkBoxUrgent.IsChecked.Value;
            po.SumCurrencyText = textEditSumLetters.Text;
            if (int.TryParse(textEditCurrencyCode.Text, out i)) po.Currency = i;
            if (Decimal.TryParse(textEditSum.Text, out d)) po.Sum = d;
            po.Payer = textEditPayerName.Text;
            if (decimal.TryParse(comboBoxEditPayerDepositNumber.Text, out d)) po.PayerDepositNumber = d;
            //miss textEditPayerBank.Text - it's our bank always
            //miss textEditPayerBankCode.Text - it's our bank always
            po.BenefBankName = comboBoxEditBenefBank.Text;
            if (decimal.TryParse(textEditBenefBankCode.Text, out d)) po.BenefBankCode = d;
            po.Benefeciar = textEditBenefName.Text;//comboBoxEditBenefName.Text;
            //if (decimal.TryParse(comboBoxEditBenefDepositNumber.Text, out d)) po.BenefDepNum = d;
            if (decimal.TryParse(textEditBenefDepositNumber.Text, out d)) po.BenefDepNum = d;
            po.PaymentAllocation = textEditPaymentAllocation.Text;
            if (decimal.TryParse(textEditPayerUNP.Text, out d)) po.PayerUNP = d;
            if (decimal.TryParse(textEditBenefUNP.Text, out d)) po.BenefUNP = d;

            return po;
        }

        private static void ShowErrors(IEnumerable<string> errLst)
        {
            var msg = new StringBuilder();
            foreach (var err in errLst)
            {
                if (msg.Length > 0) msg.Append(Environment.NewLine);
                msg.Append(err);
            }

            DXMessageBox.Show(msg.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private List<string> ValidatePaymentOrderForm()
        {
            DateTime d;

            var errLst = new List<string>();

            if (textEditPaymentOrderNumber.Text.Length == 0)
            {
                errLst.Add("Поле \"Платёжное поручение №\" должно быть заполнено.");
            }

            if (dateEditDate.Text.Length == 0)
            {
                errLst.Add("Поле \"Дата\" должно быть заполнено.");
            }
            else if (DateTime.TryParse(dateEditDate.Text, out d))
            {
                if (d == DateTime.MinValue)
                {
                    errLst.Add("Поле \"Дата\" заполнено не корректно.");
                }
            }
            else
            {
                errLst.Add("Поле \"Дата\" заполнено не корректно.");
            }

            if (textEditSumLetters.Text.Length == 0)
            {
                errLst.Add("Поле \"Сумма и валюта\" должно быть заполнено.");
            }

            if (textEditSum.Text.Length == 0)
            {
                errLst.Add("Поле \"Сумма цифрами\" должно быть заполнено.");
            }

            decimal money = String.IsNullOrEmpty(textEditSum.Text.Trim()) ? 0
                                  : Decimal.Parse(textEditSum.Text, NumberStyles.Any, new CultureInfo("ru-RU"));
            if (money < 0)
            {
                errLst.Add("Введена отрицательная сумма денег.");
            }
            if (money > Decimal.Parse("922337203685477,5807"))
            {
                errLst.Add("Введена слишком большая сумма денег.");
            }

            if (textEditPayerName.Text.Length == 0)
            {
                errLst.Add("Поле \"Плательщик\" должно быть заполнено.");
            }

            if (comboBoxEditPayerDepositNumber.SelectedIndex == -1) //(comboBoxEditPayerDepositNumber.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Счёт №\" (плательщика) должно быть заполнено.");
            }

            if (textEditPayerBank.Text.Length == 0)
            {
                errLst.Add("Поле \"Банк-отправитель\" должно быть заполнено.");
            }

            if (textEditPayerBankCode.Text.Length == 0)
            {
                errLst.Add("Поле \"Код банка\" (банка-отправителя) должно быть заполнено.");
            }

            if (comboBoxEditBenefBank.SelectedIndex == -1)//(comboBoxEditBenefBank.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Банк-получатель\" должно быть заполнено.");
            }

            if (textEditBenefBankCode.Text.Length == 0)
            {
                errLst.Add("Поле \"Код банка\" (банка-получателя) должно быть заполнено.");
            }

            if (comboBoxEditBenefName.SelectedIndex == -1 && String.IsNullOrEmpty(textEditBenefName.Text.Trim()))//(comboBoxEditBenefName.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Бенефициар\" должно быть заполнено.");
            }

            if (comboBoxEditBenefDepositNumber.SelectedIndex == -1 && String.IsNullOrEmpty(textEditBenefDepositNumber.Text.Trim()))//(comboBoxEditBenefDepositNumber.Text.Trim().Length == 0)
            {
                errLst.Add("Поле \"Счёт №\" (бенефициара) должно быть заполнено.");
            }

            if (textEditPaymentAllocation.Text.Length == 0)
            {
                errLst.Add("Поле \"Назначение платежа\" должно быть заполнено.");
            }

            if (textEditPayerUNP.Text.Length == 0)
            {
                errLst.Add("Поле \"УНП плательщика\" должно быть заполнено.");
            }
            else if (textEditPayerUNP.Text.Length != 9)
            {
                errLst.Add("Поле \"УНП плательщика\" должно состоять из 9 символов.");
            }

            if (textEditBenefUNP.Text.Length == 0)
            {
                errLst.Add("Поле \"УНП бенефициара\" должно быть заполнено.");
            }
            else if (textEditBenefUNP.Text.Length != 9)
            {
                errLst.Add("Поле \"УНП бенефициара\" должно состоять из 9 символов.");
            }
            if (textEditBenefUNP.Text == textEditPayerUNP.Text)
            {
                errLst.Add("Поля \"УНП бенефициара\" и \"УНП плательщика\" не должны совпадать.");
            }

            return errLst;
        }

        private void ButtonSavePO_Click(object sender, RoutedEventArgs e)
        {
            PaymentOrder po = null;
            try
            {
                po = ParsePaymentOrder();

            }
            catch (Exception)
            {
                DXMessageBox.Show("Ошибка чтения формы платёжного поручения", "Ошибка",
                                 MessageBoxButton.OK, MessageBoxImage.Error);
            }

            if (po != null)
            {
                var sfd = new SaveFileDialog
                            {
                                DefaultExt = "xml",
                                Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*",
                                FilterIndex = 1,
                                RestoreDirectory = true
                            };
                var sfdRes = sfd.ShowDialog();
                if (sfdRes.Value) SavePaymentOrderToFile(po, sfd.FileName);
            }

        }

        private void ButtonLoadPO_Click(object sender, RoutedEventArgs e)
        {

            var ofd = new OpenFileDialog
                                   {
                                       CheckFileExists = true,
                                       Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*",
                                       FilterIndex = 1,
                                       RestoreDirectory = true
                                   };

            if (ofd.ShowDialog().Value)
            {
                try
                {
                    var po = LoadPaymentOrderFromFile(ofd.FileName);
                    //po.Number = Generator.PaymentOrderNumberGenerator(po.PayerUNP); //update number
                    FillPaymentOrderForm(po);
                }
                catch (Exception ex)
                {
                    DXMessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

        }

        private void ClearPaymentOrderForm()
        {

            textEditPaymentOrderNumber.Text = "";
            dateEditDate.Text = DateTime.Today.ToShortDateString();
            checkBoxUrgent.IsChecked = false;
            textEditSumLetters.Text = "";
            textEditCurrencyCode.Text = "974"; //BYR
            textEditSum.Text = "";
            //textEditPayerName.Text = "";
            comboBoxEditPayerDepositNumber.Text = "";
            //textEditPayerBank.Text = "";
            //textEditPayerBank.Text = "";
            comboBoxEditBenefBank.Text = "";
            textEditBenefBankCode.Text = "";

            comboBoxEditBenefName.Text = "";
            //comboBoxEditBenefName.SelectedIndex = -1;
            //textEditBenefName.Text = "";
            comboBoxEditBenefDepositNumber.Text = "";
            //comboBoxEditBenefDepositNumber.SelectedIndex = -1;
            //textEditBenefDepositNumber.Text = "";
            textEditPaymentAllocation.Text = "";
            //textEditPayerUNP.Text = "";
            textEditBenefUNP.Text = "";
            textEditPaymentOrderNumber.Text = Generator.PaymentOrderNumberGenerator(Decimal.Parse(textEditPayerUNP.Text)).ToString();
        }

        private void FillPaymentOrderForm(PaymentOrder po)
        {
            textEditPaymentOrderNumber.Text = Generator.PaymentOrderNumberGenerator(Decimal.Parse(textEditPayerUNP.Text)).ToString(); //po.Number.ToString();
            //dateEditDate.Text = po.Date.Date.ToShortDateString(); //TODO: STRING FORMAT - ??
            dateEditDate.Text = DateTime.Now.ToShortDateString();
            checkBoxUrgent.IsChecked = po.Urgent;
            textEditSumLetters.Text = po.SumCurrencyText;
            textEditCurrencyCode.Text = po.Currency.ToString();
            textEditSum.Text = po.Sum.ToString();
            //textEditPayerName.Text = po.Payer;
            SelectComboboxItemIfExists(comboBoxEditPayerDepositNumber, po.PayerDepositNumber.ToString(), false, null);
            // textEditPayerBank.Text - hardcoded!
            // textEditPayerBankCode.Text - hardcoded!
            SelectComboboxItemIfExists(comboBoxEditBenefBank, po.BenefBankName, false, null);
            textEditBenefBankCode.Text = po.BenefBankCode.ToString();
            SelectComboboxItemIfExists(comboBoxEditBenefName, po.Benefeciar, true, textEditBenefName);
            SelectComboboxItemIfExists(comboBoxEditBenefDepositNumber, po.BenefDepNum.ToString(), true, textEditBenefDepositNumber);
            textEditPaymentAllocation.Text = po.PaymentAllocation;
            //textEditPayerUNP.Text = po.PayerUNP.ToString();
            textEditBenefUNP.Text = po.BenefUNP.ToString();
        }

        private static void SelectComboboxItemIfExists(ComboBoxEdit cb, string itemValue, bool fillIfNotFound, TextEdit textEdit)
        {

            bool isFound = false;
            if (cb.ItemsSource != null)
            {
                foreach (var item in cb.ItemsSource)
                {
                    if (item.GetType().GetProperty(cb.DisplayMember).GetValue(item, null).ToString().Equals(itemValue))
                    {
                        cb.SelectedItem = item;
                        isFound = true;
                        break;
                    }
                }
            }
            else if (cb.Items != null)
            {
                foreach (var item in cb.Items)
                {
                    if (item.ToString().Equals(itemValue))
                    {
                        cb.SelectedItem = item;
                        isFound = true;
                        break;
                    }
                }
            }

            if (fillIfNotFound && !isFound)
            {
                //Partner partner = null;
                //if (cb.Name == "comboBoxEditBenefName")
                //{
                //    partner = new Partner
                //                {
                //                    Id = Guid.NewGuid(),
                //                    IdClient = clientId,
                //                    Name = itemValue,
                //                };
                //    partners.Add(partner);
                //    cb.SelectedItem = partner;
                //}
                //if (cb.Name == "comboBoxEditBenefDepositNumber")
                //{
                //    var d = new PartnerDeposit()
                //    {
                //        Id = Guid.NewGuid(),
                //        IdPartner = partner.Id,
                //        Number = Decimal.Parse(itemValue)
                //    };
                //    //partners.Add(d);
                //    ((Partner)comboBoxEditBenefDepositNumber.SelectedItem).PartnerDeposits.ToList().Add();
                //    cb.SelectedItem = d;
                //}

                cb.Text = "";
                ////cb.Items.Insert(0, itemValue);

                textEdit.Text = itemValue;
                //cb.EditValue = itemValue;
            }
        }

        private void ButtonClearPO_Click(object sender, RoutedEventArgs e)
        {
            if (DXMessageBox.Show("Вы уверены, что вы хотите очистить форму?", "Очистка формы", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                ClearPaymentOrderForm();
            }
        }

        private void ButtonSavePartner_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var errLst = new List<string>();
                if (comboBoxEditBenefName.SelectedIndex == -1 && String.IsNullOrEmpty(textEditBenefName.Text.Trim()))//(comboBoxEditBenefName.Text.Trim().Length == 0)
                {
                    errLst.Add("Поле \"Бенефициар\" должно быть заполнено.");
                }
                if (textEditBenefUNP.Text.Length == 0)
                {
                    errLst.Add("Поле \"УНП бенефициара\" должно быть заполнено.");
                }
                else if (textEditBenefUNP.Text.Length != 9)
                {
                    errLst.Add("Поле \"УНП бенефициара\" должно состоять из 9 символов.");
                }
                if (textEditBenefUNP.Text == textEditPayerUNP.Text)
                {
                    errLst.Add("Поля \"УНП бенефициара\" и \"УНП плательщика\" не должны совпадать.");
                }
                if (comboBoxEditBenefBank.SelectedIndex == -1)//(comboBoxEditBenefBank.Text.Trim().Length == 0)
                {
                    errLst.Add("Поле \"Банк-получатель\" должно быть заполнено.");
                }
                if (comboBoxEditBenefDepositNumber.SelectedIndex == -1 && String.IsNullOrEmpty(textEditBenefDepositNumber.Text.Trim()))//(comboBoxEditBenefDepositNumber.Text.Trim().Length == 0)
                {
                    errLst.Add("Поле \"Счёт №\" (бенефициара) должно быть заполнено.");
                }
                if (errLst.Count > 0)
                {
                    ShowErrors(errLst);
                    return;
                }
                Partner newPartner = partners.FirstOrDefault(partner => partner.Name == textEditBenefName.Text);
                if (newPartner == null)
                {
                    newPartner = new Partner
                    {
                        Id = Guid.NewGuid(),
                        IdClient = clientId,
                        Name = textEditBenefName.Text,
                        UNP = Decimal.Parse(textEditBenefUNP.Text)
                    };
                    bankServiceClient.SavePartner(newPartner);
                    partners.Add(newPartner);
                }
                else
                {
                    var p = new Partner
                                {
                                    Id = newPartner.Id,
                                    IdClient = newPartner.IdClient,
                                    Name = newPartner.Name,
                                    UNP = Decimal.Parse(textEditBenefUNP.Text)
                                };
                    bankServiceClient.UpdatePartner(p);
                }
                PartnerDeposit newDeposit;
                if (newPartner.PartnerDeposits == null)
                {
                    newDeposit = null;
                }
                else
                {
                    newDeposit = newPartner.PartnerDeposits.FirstOrDefault(
                           partnerDeposit => partnerDeposit.Number == Decimal.Parse(textEditBenefDepositNumber.Text));
                }
                if (newDeposit == null)
                {
                    newDeposit = new PartnerDeposit
                    {
                        CurrnecyType = Int32.Parse(textEditCurrencyCode.Text),
                        Id = Guid.NewGuid(),
                        IdBank = ((Bank)comboBoxEditBenefBank.SelectedItem).Id,
                        IdPartner = newPartner.Id,
                        Number = Decimal.Parse(textEditBenefDepositNumber.Text)
                    };
                    bankServiceClient.SavePartnersDeposit(newDeposit);
                }
                else
                {
                    var dep = new PartnerDeposit
                                  {
                                      CurrnecyType = newDeposit.CurrnecyType,
                                      Id = newDeposit.Id,
                                      IdBank = ((Bank) comboBoxEditBenefBank.SelectedItem).Id,
                                      IdPartner = newDeposit.IdPartner,
                                      Number = newDeposit.Number
                                  };
                    bankServiceClient.UpdatePartnersDeposit(dep);
                }
                //LoadData();
                partners = new ObservableCollection<Partner>(bankServiceClient.GetClientPartners(clientId));
                comboBoxEditBenefName.ItemsSource = partners;
                DXMessageBox.Show("Контрагент сохранён", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #region "utility"

        private static byte[] ReadPrivateKey()
        {
            var fileStream = new FileStream(PrivateKeyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var tmpPrivateKey = new byte[fileStream.Length];
            fileStream.Read(tmpPrivateKey, 0, (int)fileStream.Length);
            fileStream.Close();

            return tmpPrivateKey;
        }


        private static void SavePaymentOrderToFile(PaymentOrder po, string path)
        {
            var sr = new XmlSerializer(typeof(PaymentOrder));

            var streamWriter = new StreamWriter(File.Open(path, FileMode.Create));
            sr.Serialize(streamWriter, po);
            streamWriter.Close();
        }

        private static PaymentOrder LoadPaymentOrderFromFile(string path)
        {
            var serializer = new XmlSerializer(typeof(PaymentOrder));
            var sr = new StreamReader(path);
            var po = (PaymentOrder)serializer.Deserialize(sr);
            sr.Close();

            return po;
        }
        #endregion

        private void BarButtonItemGetPaymentOrderStatus_ItemClick(object sender, ItemClickEventArgs e)
        {
            var statuses = new StatusesPopup(bankServiceClient, clientName, clientUnp, clientId);
            statuses.ShowDialog();
            if (statuses.PaymentOrderForCopy != null)
            {
                FillPaymentOrderForm(statuses.PaymentOrderForCopy);
            }
        }

        private void BarButtonItemGetTransactions_ItemClick(object sender, ItemClickEventArgs e)
        {
            (new TransactionsWindow(bankServiceClient, clientName, clientUnp, clientId)).ShowDialog();
        }

        private void BarButtonItemExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            Close();
        }

        private void BarButtonItemPaymentOrderPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                List<string> errLst = ValidatePaymentOrderForm();

                if (errLst.Count > 0)
                {
                    ShowErrors(errLst);
                }
                else
                {
                    var paymentOrder = new PaymentOrder
                    {
                        BenefBankCode = Decimal.Parse(textEditBenefBankCode.Text),
                        BenefBankName = ((Bank)comboBoxEditBenefBank.EditValue).Name,
                        BenefDepNum = Decimal.Parse(textEditBenefDepositNumber.Text),
                        Benefeciar = textEditBenefName.Text,
                        BenefUNP = Decimal.Parse(textEditBenefUNP.Text),
                        Currency = int.Parse(textEditCurrencyCode.Text),
                        Date = dateEditDate.DateTime,
                        Number = int.Parse(textEditPaymentOrderNumber.Text),
                        Payer = textEditPayerName.Text,
                        PayerDepositNumber = ((Deposit)comboBoxEditPayerDepositNumber.EditValue).Number,
                        PayerUNP = Decimal.Parse(textEditPayerUNP.Text),
                        PaymentAllocation = textEditPaymentAllocation.Text,
                        Sum = Decimal.Parse(textEditSum.Text),
                        SumCurrencyText = textEditSumLetters.Text,
                        Id = Guid.NewGuid()
                    };
                    if (checkBoxUrgent.IsChecked != null) paymentOrder.Urgent = (bool)checkBoxUrgent.IsChecked;
                    var pw = new PrintingWindow
                    {
                        DataContext = paymentOrder
                    };
                    pw.ShowDialog();
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //private static bool CheckSumLength(TextEdit textEdit)
        //{
        //    if (textEdit.Text.IndexOf(',') != -1)
        //    {
        //        if (textEdit.Text.Substring(0, textEdit.Text.IndexOf(',')).Length > 13)
        //        {
        //            //DXMessageBox.Show("Слишком большая сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        //            return false;
        //        }
        //        return true;
        //    }
        //    if (textEdit.Text.IndexOf('.') != -1)
        //    {
        //        if (textEdit.Text.Substring(0, textEdit.Text.IndexOf('.')).Length > 13)
        //        {
        //            //DXMessageBox.Show("Слишком большая сумма денег", "Ошибка", MessageBoxButton.OK,
        //            //                  MessageBoxImage.Error);
        //            return false;
        //        }
        //        return true;
        //    }
        //    if (textEdit.Text.Length > 13)
        //    {
        //        //DXMessageBox.Show("Слишком большая сумма денег", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        //        return false;
        //    }
        //    return true;
        //}
    }
}